package _14_网络编程._2_TCP编程.多线程.非线程池;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 总结：
 *      使用Java进行TCP编程时，需要使用Socket模型
 *
 *      * 服务器端使用ServerSocket监听指定端口
 *      * 客户端使用Socket(InetAddress, port)连接服务器
 *      * 服务器端用accept()接受连接并返回Socket
 *      * 双方通过Socket打开InputStream/OutputStream读写数据
 *      * 服务器端通常使用多线程同时处理多个客户端连接，利用线程池可大幅提升效率
 *      * flush()用户强制输出缓冲区到网络
 *
 *      参考 1 ：https://www.liaoxuefeng.com/wiki/1252599548343744/1305207629676577 （廖雪峰）
 *      参考 2 ：https://www.jb51.net/article/191645.htm
 *      https://www.jb51.net/article/107596.htm
 *
 */
public class Client {

    public static void main(String[] args) throws IOException {
        //服务器地址为"localhost"，表示本机地址，端口号6666
        //如果连接成功，返回一个socket实例，用户后续通信
        Socket socket = new Socket("localhost",6666);

        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputSteam = socket.getOutputStream()){
                handle(inputStream,outputSteam);
            }
        }

        socket.close();
        System.out.println("disconnected.");
    }

    private static void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(System.in);
        System.out.println("[server] " + bufferedReader.readLine());

        for(;;){
            System.out.println(">>> ");
            String str = scanner.nextLine();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            bufferedWriter.flush();

            String resp = bufferedReader.readLine();
            System.out.println("<<< ");
            if(resp.equals("bye")){
                break;
            }
        }
    }


}
